import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Website } from '@/data/config'

export const useAppStore = defineStore('app', () => {
  // 状态
  const searchQuery = ref('')
  const activeCategory = ref('all')
  const isLoading = ref(false)
  const filteredWebsites = ref<Website[]>([])
  const favorites = ref<number[]>([])
  const searchHistory = ref<string[]>([])

  // 计算属性
  const hasResults = computed(() => filteredWebsites.value.length > 0)
  
  const isFavorite = computed(() => (websiteId: number) => {
    return favorites.value.includes(websiteId)
  })

  // Actions
  const setSearchQuery = (query: string) => {
    searchQuery.value = query
    if (query.trim()) {
      addSearchHistory(query.trim())
    }
  }

  const setActiveCategory = (category: string) => {
    activeCategory.value = category
  }

  const setLoading = (loading: boolean) => {
    isLoading.value = loading
  }

  const setFilteredWebsites = (websites: Website[]) => {
    filteredWebsites.value = websites
  }

  const resetFilters = () => {
    searchQuery.value = ''
    activeCategory.value = 'all'
  }

  const toggleFavorite = (websiteId: number) => {
    const index = favorites.value.indexOf(websiteId)
    if (index > -1) {
      favorites.value.splice(index, 1)
    } else {
      favorites.value.push(websiteId)
    }
  }

  const addSearchHistory = (query: string) => {
    const newHistory = [query, ...searchHistory.value.filter(item => item !== query)].slice(0, 10)
    searchHistory.value = newHistory
  }

  return {
    // 状态
    searchQuery,
    activeCategory,
    isLoading,
    filteredWebsites,
    favorites,
    searchHistory,
    
    // 计算属性
    hasResults,
    isFavorite,
    
    // Actions
    setSearchQuery,
    setActiveCategory,
    setLoading,
    setFilteredWebsites,
    resetFilters,
    toggleFavorite,
    addSearchHistory
  }
})